<template>
	<div>
    <div id="p-msgCenter">
        <!-- top -->
		<van-nav-bar class="header" :border="false">
			<div class="title" slot="title">消息</div>
		</van-nav-bar>
		<div class="top">
			<div class="wrap flex flex-center-y">
				<div class="item">
					<dd class="pic" @click="toNotify()">
						<img src="@/assets/img/public/clock.png">
						<dot width="10" height="10" v-if="noticeHot"></dot>
					</dd>
					<p>系统通知</p>
				</div>
				<div class="line"></div>
				<div class="item" @click="advisory()">
					<dd class="pic">
						<img src="@/assets/img/public/contractService.png">
						<i class="warn" v-if="$store.state.hot2"></i>
					</dd>
					<p>联系客服</p>
				</div>
			</div>
		</div>
		<!-- 列表 -->
		<div class="temp"></div>
<!-- 		<button
            @click="test()"
            type="button"
            name="button"
            style="padding:10px">测试
        </button> -->
		<ul class="list" id="list">
			<none msg="暂无消息" v-if="formData.length==0"></none>
			<div v-else style="padding-bottom: 1rem;">
				<van-swipe-cell
					@click.native="toChat(item.groupid,item.orderUid,item.groupname)"
					:right-width="140"
					v-for="(item,index) in formData"
					:key="item.groupid"
					v-if="!item.delete"
					:on-close="onClose">
					<van-cell-group>
						<li
							class="flex flex-center-y"
							:style="{backgroundColor:item.top==true?'#F9F9F9':'#fff'}" >
							<dd class="pic flex flex-center-x flex-center-y">
								<img src="@/assets/img/performance/msgCenter/profile.png">
								<!-- 未读数 -->
								<i 
									class="warn" 
									v-if="item.newMsg">{{item.newMsg|max99}}
								</i>
							</dd>
							<div class="text">
								<h3>{{item.groupname}}</h3>
								<p v-if="item.lastName">
									<span class="red">{{item.groupid|atMe}}</span>
									{{item.lastName}}:{{item.lastMsg}}
								</p>
							</div>
							<div class="right">
								<h3>{{item.lastTime}}</h3>
								<!-- <h3>{{item.lastTime|timer}}</h3> -->
								<img src="@/assets/img/performance/msgCenter/mute.png" v-if="item.mute">
							</div>
						</li>
					</van-cell-group>
					<div slot="right" class="slide">
						<span @touchstart.stop="top(item.groupid,index,false)" v-if="item.top">取消置顶</span>
						<span @touchstart.stop="top(item.groupid,index,true)" v-else>置顶</span>
						<span @touchstart.stop="clearHot(item.groupid),del(item.groupid,true,true,item)">删除</span>
					</div>
				</van-swipe-cell>
			</div>
		</ul>
    </div>
	<!-- 屁股 -->
	<main-nav></main-nav>
	</div>
</template>
<script>
import mainNav from "@/components/performance/mainNav";
import dot from "@/components/performance/msgCenter/dot.vue";
import none from "@/components/performance/msgCenter/none.vue";
import {getAccount,getuserUid,getPassword,getUserLogin} from '@/utils/auth.js'
import {setRemind,getRemind,isContainKey,setDelgroup,getDelgroup,unique,setAt,getAt,fileterMsg} from '@/utils/chat.js'
import {getDateDiff} from '@/utils/date.js'
import pushMsg from '@/utils/push.js'
import unread from '@/utils/unread.js'
import {AMAPKEY,asyncLoadAMAP} from '@/utils/amap.js'
import { mapMutations } from "vuex";
let map = "";
let posi = [];
let loadMap = (site) => {
	//加载地图
    let params = {
        zoom: 16,
		scrollWheel: false,
    }
    map = new AMap.Map('container', params);
	//定位
	AMap.plugin('AMap.Geolocation', function() {
		let geolocation = new AMap.Geolocation({
			enableHighAccuracy: true,//高精度定位
			timeout: 10000,
			buttonPosition:'RB',    //定位按钮的位置
			buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
			zoomToAccuracy: true,
		});
		map.addControl(geolocation);
		//定位成功
		geolocation.getCurrentPosition(function(status,result){
			console.log(status);
			console.log(result);
		})
	});
	//拖拽选址
	AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
		var positionPicker = new PositionPicker({
            mode: 'dragMap',
            map: map
        });
		//success
		positionPicker.on('success', function(positionResult) {

        });
		//error
		positionPicker.on('fail', function(positionResult) {

        });
        positionPicker.start();
	});
}
window.map_callback = () => {
    initAMapUI()
}
export default {
    components: {
        mainNav,
		dot,
		none
    },
	data(){
		return{
			formData:[
				// {
				// 	orderUid:"504010",
				// 	groupid:"80522397155329",
				// 	groupname:"嘻哈讨论组",
				// 	lastMsg:"明天见",    //最后一条聊天消息
				// 	lastName:"倪彦祖",    //最后一条信息的发送者
				// 	newMsg:true, //是否新消息
				// 	time:2019-5-1,
				// 	mute:false, //免打扰
				// 	delete:false, //是否已删除
				// }
			],
			userId:"",
			noticeHot:false, //true系统通知有红点
			hots:[], //未读消息的群组

			//@功能
			at:[],

			//预加载地图
			key:"",

			//toast
			toast:"",
			
			//other
			scroll:0,  //滚动条距离
		}
	},
	methods:{
		...mapMutations(["setTabIndexP"]),
		test:function(){
			this.$router.push({
				path:'/performance/preview',
				query:{
					bg:'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3136075639,3338708347&fm=26&gp=0.jpg',
					groupId:84058282459137
				}
			})
		},
		//加载中
		loading:function(msg){
			const toast = this.$toast.loading({
				duration: 0,
				mask: false,
				message: msg,
				forbidClick:false
			});
			return toast;
		},
		//地图预加载
		loadMap:function(){
			if(window.scriptID){
                window.map_callback()
                return
			}
			var scriptID = 'map_amp_ID'
			var amapUIJs = document.createElement('script')
			amapUIJs.src = 'https://webapi.amap.com/ui/1.0/main-async.js'
			document.body.appendChild(amapUIJs)
			amapUIJs.onload = () => {
				var scriptUrl = `https://webapi.amap.com/maps?v=1.4.13&key=${this.key}&callback=map_callback`
				var script = document.createElement('script')
				script.id = scriptID
				script.src = scriptUrl
				document.body.appendChild(script)
			}
			window.scriptID = scriptID
		},
		list:function(){
			this.formData = [];
			//this.toast = this.loading('加载中');
			//后端获取群组列表
			HTTP('group_list',{
				userUid:this.userId
			})
			.then(res=>{
				this.$toast.clear();
				if(res.code == 200){
					this.hots  = JSON.parse(window.localStorage.getItem("unread"));
					this.formData = [];
					//把后端字段拼成前端字段
					res.data.map(o=>{
						let obj = JSON.parse(o.payload);
						this.formData.push({
							orderUid:o.orderUid,
							groupid:o.groupid,
							groupname:o.groupname,
							lastName:obj?obj.ext.name:'',  //发送者
							lastTime:o.lastTime?getDateDiff(o.lastTime):'',  //发送时间
							lastMsg:obj?fileterMsg(obj):'',  //聊天记录
							newMsg:'', //红点提醒
							mute:o.notDisturb, //免打扰
							delete:o.delete, //是否已删除
							top:o.top, //是否置顶
						})
					});
					//红点提醒
					if(this.hots){
						this.hots.map(o=>{
							this.setHot(o.id,o.num);
							//已删除的群组进行恢复
							this.formData.map(p=>{
								if(p.delete){
									if(o == p.groupid){
										this.del(p.groupid,false,true);
									}
								}
							})
						})
					}
					//离顶部的位置
					this.$nextTick(()=>{
						let DOM  = document.getElementById('p-msgCenter');
						DOM.scrollTop = this.$store.state.chatScroll?this.$store.state.chatScroll:0;
						DOM.addEventListener('scroll', this.handleScroll);  //监听滚动位置
					})
					// setTimeout(()=>{
					// 	let DOM  = document.getElementById('p-msgCenter');
					// 	DOM.scrollTop = this.$store.state.chatScroll?this.$store.state.chatScroll:0;
					// 	DOM.addEventListener('scroll', this.handleScroll);  //监听滚动位置
					// },5)
				}
				else{
					this.$toast(res.msg);
				}
			})
		},
		//设置红点提醒
		setHot:function(id,num){
			this.formData.map((o,n)=>{
				if(o.groupid == id){
					//非免打扰群组
					if(!o.mute){
						if(num){
							this.formData[n].newMsg = num;
						}
						else{
							if(this.formData[n].newMsg){
								this.formData[n].newMsg = parseInt(this.formData[n].newMsg) + 1;
							}
							//为空，则为1
							else{
								this.formData[n].newMsg = 1;
							}
						}
					}
				}
			})
		},
		//清除红点
		clearHot:function(id){
			this.hots = JSON.parse(window.localStorage.getItem("unread"));
			var GroupHots = getRemind();
			//去除未读消息数
			if(this.hots){
				this.hots.map((o,n)=>{
					if(o.id == id){
						this.hots.splice(n,1);
					}
				})
				//写入缓存
				window.localStorage.setItem("unread", JSON.stringify(this.hots));
			}
			//去除红点
			if(GroupHots){
				GroupHots.map((o,n)=>{
					if(o == id){
						GroupHots.splice(n,1);
					}
				})
				setRemind(GroupHots);
			}
		},
		//移除@
		clearAt:function(id){
			this.at = getAt();
			if(this.at){
				this.at.map((o,n)=>{
					if(o == id){
						this.at.splice(n,1);
					}
				})
				setAt(this.at);
			}
		},
		//过滤消息、图片、视频、推送
		fileterMsg:function(obj){
			if(obj){
				if(obj.ext.type == 'text' || obj.ext.type == 'txt'){
					return obj.ext.content;
				}
				else if(obj.ext.type == 'image'){
					return '[图片]';
				}
				else if(obj.ext.type == 'video'){
					return '[视频]';
				}
				else if(obj.ext.type == 'map'){
					return '[位置]';
				}
				else if(obj.ext.type == 'editImg'){
					return '[图片]'
				}
                else if(obj.ext.type == 'editNone'){
                    return '[图片]'
                }
				else if(obj.ext.type == 'works'){
					return '[作品]'
				}
				else{
					return '[推送消息]';
				}
			}
		},
		//环信监听
		webIm:function(){
			this.$imconn.listen({
				//建立是否成功
				onOpened:(data)=>{
					console.log('执行onPresence方法，建立成功');
				},
				//收到消息
				onTextMessage:(data)=>{
					//自己发的消息不监听
					if(data.from != this.userId){
						console.log('消息页监听');
						console.log(data);
						//客服消息
						if(data.type == "chatroom"){
							this.$store.commit("serverHot", true);
							pushMsg(data,'chatroom');
						}
						//群组消息
						else{
							this.$store.commit("setHot", true);
							//已删除的群组进行恢复
							this.formData.map(p=>{
								if(p.delete){
									if(data.to == p.groupid){
										p.delete = false;
										this.del(p.groupid,false,false);
									}
								}
							})
							//开启红点
							this.setHot(data.to);
							unread(data.to);
							//如果有人@我
							if(data.ext.ifAt){
								//如果@的是我
								let atArr = [];
								if(getAt()){
									atArr = getAt();
								}
								data.ext.toAt.map(o=>{
									if(o == this.userId){
										atArr.push(data.to);
										let at = unique(atArr); //去重
										setAt(at); //写入缓存
									}
								})
							}
							//消息提醒
							console.log('消息提醒');
							console.log('data.ext.time:' + data.ext.time);
							console.log('当前时间戳:' + Date.parse(new Date()));
							let n = this.findIndex(this.formData,'groupid',data.to);
							this.formData[n].lastMsg = fileterMsg(data);
							this.formData[n].lastName = data.ext.name;
							let lastTimer = getDateDiff(data.ext.time?data.ext.time:Date.parse(new Date()));  //加这段是为了解决vivo显示不了时间的问题
							this.formData[n].lastTime = lastTimer?lastTimer:'刚刚';
							console.log('this.formData[n].lastTime:' + this.formData[n].lastTime);
							//写入缓存
							let groups = getRemind()?getRemind():[];
							groups.push(data.to);
							let arr = unique(groups); //去重
							setRemind(arr); //写入缓存
							//放在第一位
							var count = 0;
							var one = this.findIndex(this.formData,'groupid',data.to);
							this.formData.map(o=>{
								if(o.top){
									count++;
								}
							})
							if(!this.formData[count].top){
								if(count != one){  
									this.formData.splice(count,0,this.formData[one]);
									this.formData.splice(one+1,1);
								}
							}
							//桌面图标
							this.deskHot();
						}
					}
				},
				//收到图片消息
				onPictureMessage:(data)=>{
					//自己发的消息不监听
					if(data.from != this.userId){
						//客服消息
						if(data.type == "chatroom"){
							this.$store.commit("serverHot", true);
							pushMsg(data,'chatroom');
						}
						//群组消息
						else{
							this.$store.commit("setHot", true);
							//已删除的群组进行恢复
							this.formData.map(p=>{
								if(p.delete){
									if(data.to == p.groupid){
										p.delete = false;
										this.del(p.groupid,false,false);
									}
								}
							})
							//开启红点
							this.setHot(data.to);
							unread(data.to);
							//消息提醒
							let n = this.findIndex(this.formData,'groupid',data.to);
							this.formData[n].lastMsg = fileterMsg(data);
							this.formData[n].lastName = data.ext.name;
							let lastTimer = getDateDiff(data.ext.time?data.ext.time:Date.parse(new Date()));  //加这段是为了解决vivo显示不了时间的问题
							this.formData[n].lastTime = lastTimer?lastTimer:'刚刚';
							//写入缓存
							let groups = getRemind();
							groups.push(data.to);
							let arr = unique(groups); //去重
							setRemind(arr); //写入缓存
							//放在第一位
							var count = 0;
							var one = this.findIndex(this.formData,'groupid',data.to);
							this.formData.map(o=>{
								if(o.top){
									count++;
								}
							})
							if(!this.formData[count].top){
								if(count != one){  
									this.formData.splice(count,0,this.formData[one]);
									this.formData.splice(one+1,1);
								}
							}
							//桌面图标
							this.deskHot();
						}
					}
				}
			})
		},
		//桌面图标红点
		deskHot:function(){
			var hot = JSON.parse(window.localStorage.getItem("unread"));
			var sum = 0;
			if(hot){
				hot.map(o=>{
					sum = sum + o.num;
				})
				plus.runtime.setBadgeNumber(sum,{
					title:"我是标题",
					content:"我是内容"
				});
			}
			else{
				plus.runtime.setBadgeNumber(0,{
					title:"我是标题",
					content:"我是内容"
				});
			}
		},
		//置顶
		top:function(id,index,bool){
			HTTP('group_top',{
				userUid:this.userId,
				groupUid:id,
				flag:bool
			})
			.then(res=>{
				if(res.code == 200){
					this.$toast('置顶成功');
					this.list();
				}
				else{
					this.$toast(res.msg);
				}
			})
		},
		//移除免打扰
		change_mute:function(obj){
			HTTP('group_mute',{
				userUid:this.userId,
				groupUid:obj.groupid,
				flag:false
			})
			.then(res=>{
				if(res.code == 200){
					console.log('免打扰成功');
				}
				else{
					//this.$toast(res.msg);
				}
			})
		},
		//删除群组
		del:function(id,bool,loadList,obj){
			//如果删除的是一个免打扰群组，先恢复免打扰
			if(obj){
				if(obj.mute){
					this.change_mute(obj);
				}
			}
			//群组id,是否删除群组,请求结束是否加载列表
			HTTP('group_del',{
				userUid:this.userId,
				groupUid:id,
				isDelete:bool
			})
			.then(res=>{
				if(res.code == 200){
					if(loadList){
						this.list();
					}
				}
				else{
					this.$toast(res.msg);
				}
			})
		},
		//跳到系统通知
		toNotify:function(){
			this.$router.push('/performance/notify');
		},
		//联系客服
		advisory:function(){
			this.$store.commit("serverHot", false);
			this.$router.push('/advisory');
		},
		//跳到聊天
		toChat:function(id,orderId,title){
			this.clearHot(id);
			this.clearAt(id);
			this.$store.commit("setTitle", title);
			//记录滚动条位置
			if(this.scroll){
				this.$store.commit("setScroll", this.scroll);
			}
			//跳转
			this.$router.push({
				path:'/performance/chat',
				query:{
					id:id,
					orderId:orderId
				}
			});
			//桌面图标
			this.deskHot();
		},
		//根据id查找下标
		findIndex:function(arr,key,word){
			let t = '';
			arr.map((o,n)=>{
				if(o[key] == word){
					t = n;
				}
			})
			return t;
		},
		//系统通知红点提醒
		notice_hot:function(){
			HTTP('notice_hot',{
				userUid:this.userId
			})
			.then(res=>{
				if(res.code == 200){
					if(res.data){
						this.$store.commit("setSystemHot", true);
						this.noticeHot = true;
					}
					else{
						this.$store.commit("setSystemHot", false);
						this.noticeHot = false;
					}
				}
			})
		},
		//关闭右滑
		onClose:function(clickPosition, instance){
			setTimeout(()=>{
				instance.close();
			},100)
		},
		//连接环信
		async loginIM(){
			this.$imoption.user = getuserUid(); //环信账号
			this.$imoption.pwd = getPassword(); //环信密码
			this.$imconn.open(this.$imoption); //建立连接
		},
		//记录滚动位置
		handleScroll:function(){
			let DOM  = document.getElementById('p-msgCenter');
			this.$store.commit("setScroll", DOM.scrollTop);
			console.log(this.$store.state.chatScroll);
		},
	},
	mounted:function(){
		this.list();
		this.webIm();
		this.notice_hot(); //系统通知红点提醒
		// setTimeout(()=>{
		// 	let DOM  = document.getElementById('p-msgCenter');
		// 	DOM.scrollTop = 500;
		// 	DOM.addEventListener('scroll', this.handleScroll);  //监听滚动位置
		// },2000)
		this.loadMap();
		asyncLoadAMAP();
	},
	created:function(){
		this.loginIM(); //链接环信
		this.setTabIndexP(2)
		this.key = AMAPKEY;  //地图key
		this.userId = getuserUid(); //用户id
		//未读消息的群组
		this.hots  = getRemind();
		//setAt([]);
		//alert(getDateDiff('1560163981585'));
	},
	filters: {
		timer: function(value) {
			//今天 昨天
			let r = getDateDiff(value);
			return value?r:null;
		},
		//有@我的群组
		atMe:function(value){
			let myAt = getAt();
			if(myAt){
				if(myAt.indexOf(value) >-1){
					return '[有人@我]';
				}
				else{
					return null;
				}
			}
		},
		//未读消息最大99
		max99:function(value){
			if(value<99){
				return value
			}
			else{
				return '...'
			}
		}
	}
};
</script>
<style lang="scss" scoped>
	.red{
		color: red;
	}
	.header{
		background: $color-primary;
		.title{
			color: #fff;
		}
	}
	#p-msgCenter{
		height: 100vh;
		overflow:scroll;
		background-color: #fff;
		.temp{
			width: 100%;
			height: 0.4rem;
			background-color: #fff;
		}
		//top
		.top{
			position: relative;
			background: $color-primary;
			height: 1.8rem;
			.wrap{
				box-shadow:0 0 3px #ccc;
				position: absolute;
				top: 0;
				left: 3%;
				right: 3%;
				width: 94%;
				margin: 0 auto;
				background-color: #fff;
				padding: 0.4rem 0;
				border-radius: 4px;
				.warn{
					position: absolute;
					right: 0;
					top: 0;
					width: .2rem;
					height: .2rem;
					background-color: #ED4F52;
					border-radius: 50%;
					font-size: 0.2rem;
					border: 1px solid #fff;
				}
				.item{
					text-align: center;
					width: 50%;
					.pic{
						position: relative;
						width: 1rem;
						height: 1rem;
						margin: 0 auto;
						img{
							width: 100%;
							height: 100%;
						}
					}
					p{
						padding-top: 5px;
						color: #666;
					}
				}
				.line{
					width: 1px;
					height: 1rem;
					background-color: #eee;
				}
			}
		}
		//列表
		.list{
			li{
				background-color: #fff;
				height: 1.4rem;
				padding: 0 11px;
				.pic{
					position: relative;
					width: 0.8rem;
					height: 0.8rem;
					border-radius: 50%;
					background-color: $color-primary;
					img{
						width: 50%;
						height: 50%;
					}
					.warn{
						display: flex;
						align-items: center;
						justify-content: center;
						//padding: .08rem;
						position: absolute;
						top: -0.1rem;
						right: -0.1rem;
						color: #fff;
						width: 0.4rem;
						height: 0.4rem;
						background-color: #ED4F52;
						border-radius: 50%;
						text-align: center;
						border: 1px solid #fff;
						font-size: $fz-7;
					}
				}
				.text{
					h3{
						font-weight: normal;
						color: #333;
						font-size: $fz-3;
						padding-bottom: 4px;
						word-wrap: normal;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					p{
						color: #888;
						word-wrap: normal;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					width: calc(100% - 3rem);
					padding: 0 0.2rem;
				}
				.right{
					width: 1.8rem;
					text-align: right;
					h3{
						font-weight: normal;
						color: #888;
						font-size: $fz-6;
						padding-bottom: 5px;
					}
					img{
						width: 0.2rem;
					}
				}
			}
		}
		.slide{
			display: flex;
			span{
				text-align: center;
				height: 1.4rem;
				line-height: 1.4rem;
				width: 70px;
				color: #fff;
				z-index: 886;
			}
			span:nth-child(1){
				background-color: #F4B34C;
			}
			span:nth-child(2){
				background-color: #ED4F52;
			}
		}
	}
</style>
